package com.yanqu.road.server.manger.messagesubscribe;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.enums.eChannelType;
import com.yanqu.road.entity.messageSubscribe.entity.MessageSubscribePlayerData;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.messagesubscribe.enums.MessageSubscribeConfig;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.MD5Security;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.http.HttpHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.SortedMap;
import java.util.TreeMap;

public class DyMessageSubscribe {

    private static Logger logger = LogManager.getLogger(DyMessageSubscribe.class);

    private static int gameId = 180;

    private static String sign = "g_tX23pC9c2256ea,vy_58RPQR6AZ!r~";

    public static void sendMessageSubscribe(MessageSubscribeConfig templateConfig, String appExt, String platformUserId, Object data, boolean isRetry) {
        if (!isSwitch()) {
            return;
        }
        if (StringUtils.isNullOrEmpty(appExt) || templateConfig.getDyTemplateId().isEmpty() || platformUserId.isEmpty()) {
            return;
        }
        try {
            String url = ChannelConfig.DOUYIN_SEND_NOTICE_URL;
            if(url == null){
                url = "https://gapih5.37.com/api/v1/dy/templateMessageSend";
            }
            JSONObject paramObj = new JSONObject();
            paramObj.put("app_ext", appExt);
            paramObj.put("game_id", gameId);
            paramObj.put("uid", platformUserId);
            paramObj.put("tpl_id", templateConfig.getDyTemplateId());
            paramObj.put("data", data == null ? "" : data);
            paramObj.put("page", "");
            int now = DateHelper.getCurrentSecond();
            paramObj.put("time", now);
            StringBuffer sb = new StringBuffer();
            sb.append("app_ext=").append(appExt).append("&")
                    .append("data=").append(JSONObject.toJSONString(data)).append("&")
                    .append("game_id=").append(gameId).append("&")
                    .append("page=").append("").append("&")
                    .append("time=").append(now).append("&")
                    .append("tpl_id=").append(templateConfig.getDyTemplateId()).append("&")
                    .append("uid=").append(platformUserId).append("&")
                    .append(sign);
            String signValue = MD5Security.md5(sb.toString()).toLowerCase();
            paramObj.put("sign", signValue);
            String result = HttpHelper.doPostJson(url, paramObj.toJSONString(), "UTF-8");
            if (StringUtils.isNullOrEmpty(result)) {
                logger.info("发送抖音订阅消息 异常。 url:{}, paramObj:{}", url, paramObj.toJSONString());
                return;
            }
            logger.info("发送抖音订阅消息 isRetry :{}, result:{}", isRetry, result);
            JSONObject resultObject = JSONObject.parseObject(result);
            JSONObject ret = resultObject.getJSONObject("data");
            if (ret != null) {
                int err_no = ret.getIntValue("err_no");
                if (err_no != 0 && !isRetry) {
                    if (err_no == 1001) {
                        // 重新获取accessToken
                        sendMessageSubscribe(templateConfig, appExt, platformUserId, data, true);
                        return;
                    }
                }
                if (err_no != 0) {
                    logger.warn("发送抖音订阅消息 {}  失败 templateId:{}, platformUserId:{},isRetry:{},err_no:{}", templateConfig.getGameTitle(), templateConfig.getDyTemplateId(), platformUserId, isRetry, err_no);
                }
            }
        } catch (Exception e) {
            logger.error("发送抖音订阅消息 templateId:{}, platformUserId:{}", templateConfig.getDyTemplateId(), platformUserId, e);
        }
    }

    /**
     * 是否开启这个功能
     * 1. 判断渠道号、是否是正式环境
     *
     * @return
     */
    public static boolean isSwitch() {
        // TODO 判断渠道号、是否是正式环境
        long serverId = ConfigHelper.getLong("serverId");
        int channelId = ServerListMgr.getChannelId(serverId);
        if (channelId == eChannelType.Mobile_DY.getValue()) {
            return true;
        }
        return false;
    }
}
